<template>
  <div class="history-sql-container">
    <el-card class="box-card">
      <template #header>
        <div class="list-header">
          <h2>生成历史SQL</h2>
          <div class="header-actions">
            <el-tooltip content="关闭" placement="bottom">
              <el-button
                  type="info"
                  @click="$emit('closeGeneratedHistorySql')"
                  size="small"
                  class="icon-btn"
              >
                <el-icon><Close /></el-icon>
              </el-button>
            </el-tooltip>
          </div>
        </div>
      </template>

      <div class="content-layout">
        <!-- 左侧表单 -->
        <div class="form-container">
          <el-form :model="searchForm" class="search-form" :class="{ 'form-disabled': progressVisible }">
        <el-form-item label="地址名称" label-width="100px">
          <el-select
            v-model="searchForm.addressName"
            placeholder="请选择地址"
            filterable
            clearable
            @change="handleAddressChange"
            style="width: 100%"
            :disabled="progressVisible"
          >
            <el-option
              v-for="addr in addressList"
              :key="addr.id"
              :label="addr.name"
              :value="addr.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="库名" label-width="100px">
          <el-select
            v-model="searchForm.dbName"
            placeholder="请选择库名"
            filterable
            clearable
            @change="handleDbChange"
            style="width: 100%"
            :disabled="progressVisible"
          >
            <el-option
              v-for="db in dbOptions"
              :key="db"
              :label="db"
              :value="db"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="表名" label-width="100px">
          <el-select
            v-model="searchForm.tableName"
            placeholder="请选择表名"
            filterable
            clearable
            :disabled="!searchForm.dbName || progressVisible"
            style="width: 100%"
          >
            <el-option
              v-for="table in tableOptions"
              :key="table"
              :label="table"
              :value="table"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" label-width="100px">
          <el-date-picker
            v-model="searchForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
            :disabled="progressVisible"
          />
        </el-form-item>
        <el-form-item label="结束时间" label-width="100px">
          <el-date-picker
            v-model="searchForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
            :disabled="progressVisible"
          />
        </el-form-item>
            <el-form-item label-width="100px">
              <div class="button-group">
                <el-button type="primary" @click="handleSearch" :loading="tableLoading || progressVisible" :disabled="tableLoading || progressVisible" :icon="Plus">生成</el-button>
                <el-button @click="resetForm" :disabled="tableLoading || progressVisible" :icon="RefreshRight">重置</el-button>
              </div>
            </el-form-item>
          </el-form>
        </div>

        <!-- 右侧进度指示器 -->
        <div class="progress-container">
          <div class="progress-card">
            <div class="progress-title">实时生成进度</div>
            <div class="progress-metrics">
              <div class="metric-item">
                <div class="metric-label">生成SQL数量</div>
                <div class="metric-value">{{ totalSql }}</div>
              </div>
              <div class="metric-item">
                <div class="metric-label">消费SQL数量</div>
                <div class="metric-value">{{ consumptionTotalSql }}</div>
              </div>
            </div>
            <div class="progress-animation">
              <div class="pulse-container" v-if="progressVisible">
                <div class="pulse-circle"></div>
                <div class="pulse-circle"></div>
                <div class="pulse-circle"></div>
              </div>
            </div>
            <div class="progress-label">
              {{ progressVisible ? '正在实时生成SQL...' : '等待生成SQL' }}
            </div>
            <div class="progress-actions">
              <el-button
                type="primary"
                size="small"
                @click="handleManualRefresh"
                :loading="refreshLoading"
                :disabled="!searchForm.addressName || !searchForm.dbName"
                :icon="Refresh"
              >
                手动查询进度
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, onBeforeUnmount } from 'vue'
import { Close, RefreshRight, Plus, Refresh } from '@element-plus/icons-vue'
import api from '@/api'
import { ElMessage, ElLoading } from 'element-plus'

// 搜索表单数据
const searchForm = reactive({
  addressName: '',
  id: '',
  host: '',
  port: '',
  userName: '',
  passWord: '',
  dbName: '',
  tableName: '',
  startTime: '',
  endTime: ''
})

// 数据
const addressList = ref([])
const dbOptions = ref([])
const tableOptions = ref([])
const selectedAddress = ref(null)
const tableLoading = ref(false)
const progressVisible = ref(false)
const refreshLoading = ref(false)

// 进度数据
const totalSql = ref(0)
const consumptionTotalSql = ref(0)
const progressTimer = ref(null)

// 获取地址列表
const fetchAddressList = async () => {
  try {
    const data = { deleted: 0 }
    const response = await api.binlog.list(data, 1, 1000)
    if (response.code === 200) {
      addressList.value = response.data.records || []
    }
  } catch (error) {
    console.error('获取地址列表失败:', error)
    ElMessage.error('获取地址列表失败')
  }
}

// 获取数据库列表
const fetchDatabaseList = async () => {
  if (!selectedAddress.value) return

  try {
    const { id, host, port, userName, passWord } = selectedAddress.value
    const response = await api.binlog.getDataBaseList({ id, host, port, userName, passWord })

    if (response.code === 200) {
      dbOptions.value = response.data || []
      if (selectedAddress.value.dbName) {
        searchForm.dbName = selectedAddress.value.dbName
      }
    } else {
      ElMessage.error(response.msg || '获取数据库列表失败')
      dbOptions.value = []
    }
  } catch (error) {
    console.error('获取数据库列表失败:', error)
    ElMessage.error('获取数据库列表失败')
    dbOptions.value = []
  }
}

// 获取表列表
const fetchTableList = async (dbName) => {
  if (!selectedAddress.value || !dbName) {
    tableOptions.value = []
    return
  }

  try {
    const { id, host, port, userName, passWord } = selectedAddress.value
    const response = await api.binlog.getDataTableList({
      id, host, port, userName, passWord, dbName
    })

    if (response.code === 200) {
      tableOptions.value = response.data || []
    } else {
      ElMessage.error(response.msg || '获取表列表失败')
      tableOptions.value = []
    }
  } catch (error) {
    console.error('获取表列表失败:', error)
    ElMessage.error('获取表列表失败')
    tableOptions.value = []
  }
}

// 处理地址选择变化
const handleAddressChange = (addressId) => {
  if (!addressId) {
    searchForm.dbName = ''
    searchForm.tableName = ''
    searchForm.host = ''
    searchForm.port = ''
    searchForm.userName = ''
    searchForm.passWord = ''
    searchForm.id = ''
    dbOptions.value = []
    tableOptions.value = []
    selectedAddress.value = null
    return
  }

  selectedAddress.value = addressList.value.find(addr => addr.id === addressId)
  if (selectedAddress.value) {
    searchForm.host = selectedAddress.value.host
    searchForm.port = selectedAddress.value.port
    searchForm.userName = selectedAddress.value.userName
    searchForm.passWord = selectedAddress.value.passWord
    searchForm.id = selectedAddress.value.id

    fetchDatabaseList().then(() => {
      if (selectedAddress.value?.dbName && dbOptions.value.includes(selectedAddress.value.dbName)) {
        searchForm.dbName = selectedAddress.value.dbName
        fetchTableList(selectedAddress.value.dbName).then(() => {
          if (selectedAddress.value?.tableName && tableOptions.value.includes(selectedAddress.value.tableName)) {
            searchForm.tableName = selectedAddress.value.tableName
          }
        })
      }
    })
  }
}

// 处理数据库选择变化
const handleDbChange = async (dbName) => {
  searchForm.tableName = ''
  tableOptions.value = []
  await nextTick()

  if (dbName && selectedAddress.value) {
    try {
      await fetchTableList(dbName)
    } catch (error) {
      console.error('获取表列表失败:', error)
      ElMessage.error(`获取表列表失败: ${error.message || '未知错误'}`)
    }
  }
}

// 获取实时进度
const fetchProgress = async () => {
  if (!progressVisible.value && !refreshLoading.value) return

  try {
    const data = {
      id: searchForm.id,
      name: selectedAddress.value?.name || '',
      dbName: searchForm.dbName,
      tableName: searchForm.tableName
    }

    const response = await api.binlog.getProgress(data)

    if (response.code === 200) {
      totalSql.value = response.data.totalSql || 0
      consumptionTotalSql.value = response.data.consumptionTotalSql || 0

      if (refreshLoading.value) {
        ElMessage.success('进度查询成功')
        refreshLoading.value = false
      }

      if (totalSql.value === 0 && consumptionTotalSql.value === 0) {
        if (progressTimer.value && progressTimer.value.startTime &&
            (Date.now() - progressTimer.value.startTime > 10000) &&
            progressTimer.value.emptyCount > 5) {
          stopProgressUpdate()
          return
        }

        if (!progressTimer.value.emptyCount) progressTimer.value.emptyCount = 0
        progressTimer.value.emptyCount++
      } else {
        if (progressTimer.value) progressTimer.value.emptyCount = 0

        if (consumptionTotalSql.value === totalSql.value && totalSql.value > 0) {
          setTimeout(() => {
            fetchProgress().then(() => {
              if (consumptionTotalSql.value === totalSql.value && totalSql.value > 0) {
                stopProgressUpdate()
              }
            })
          }, 2000)
        }
      }
    }
  } catch (error) {
    console.error('获取进度失败:', error)
    if (refreshLoading.value) {
      ElMessage.error('获取进度失败')
      refreshLoading.value = false
    }
  }
}

// 手动刷新进度
const handleManualRefresh = async () => {
  if (!searchForm.addressName || !searchForm.dbName) {
    ElMessage.warning('请选择地址和库名')
    return
  }

  refreshLoading.value = true
  await fetchProgress()
}

// 开始进度更新
const startProgressUpdate = () => {
  stopProgressUpdate()
  totalSql.value = 0
  consumptionTotalSql.value = 0

  progressTimer.value = {
    timer: setInterval(fetchProgress, 1000),
    startTime: Date.now(),
    emptyCount: 0
  }

  fetchProgress()
}

// 停止进度更新
const stopProgressUpdate = () => {
  if (progressTimer.value && progressTimer.value.timer) {
    clearInterval(progressTimer.value.timer)
    progressTimer.value = null
    setTimeout(() => {
      progressVisible.value = false
    }, 1000)
  }
}

// 生成SQL
const fetchHistorySqlList = async () => {
  tableLoading.value = true
  try {
    const data = {
      id: searchForm.id,
      addressName: searchForm.addressName,
      host: searchForm.host,
      port: searchForm.port,
      userName: searchForm.userName,
      passWord: searchForm.passWord,
      dbName: searchForm.dbName,
      tableName: searchForm.tableName,
      startTime: searchForm.startTime,
      endTime: searchForm.endTime
    }

    const response = await api.binlog.generateSql(data)

    if (response.code === 401 || response.code === 403) {
      ElMessage.error('认证失败，请重新登录')
      return
    }

    if (response.code === 200) {
      ElMessage.success('SQL生成任务已启动')
      progressVisible.value = true
      startProgressUpdate()
    } else {
      ElMessage.error(response.msg || 'SQL生成失败')
    }
  } catch (error) {
    console.error('SQL生成失败:', error)
    ElMessage.error('SQL生成失败')
  } finally {
    tableLoading.value = false
  }
}

// 处理搜索按钮点击
const handleSearch = () => {
  if (!searchForm.addressName) {
    ElMessage.warning('请选择地址')
    return
  }
  if (!searchForm.dbName) {
    ElMessage.warning('请选择库名')
    return
  }
  if (!searchForm.startTime || !searchForm.endTime) {
    ElMessage.warning('请选择开始和结束时间')
    return
  }

  const startTime = new Date(searchForm.startTime).getTime()
  const endTime = new Date(searchForm.endTime).getTime()
  if (startTime >= endTime) {
    ElMessage.warning('开始时间必须早于结束时间')
    return
  }

  fetchHistorySqlList()
}

// 重置表单
const resetForm = () => {
  const addressId = searchForm.addressName
  Object.assign(searchForm, {
    addressName: addressId,
    dbName: '',
    tableName: '',
    startTime: '',
    endTime: ''
  })

  if (addressId && selectedAddress.value) {
    fetchDatabaseList()
  } else {
    dbOptions.value = []
    tableOptions.value = []
  }
}

// 组件挂载时获取地址列表
onMounted(() => {
  fetchAddressList()
})

// 组件卸载前清除定时器
onBeforeUnmount(() => {
  stopProgressUpdate()
})
</script>

<style scoped>
.history-sql-container {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
  position: relative;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.list-header h2 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.icon-btn {
  width: 32px;
  height: 32px;
  padding: 0;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.icon-btn:hover {
  transform: scale(1.1);
}

.icon-btn .el-icon {
  font-size: 16px;
}

/* 左右布局 */
.content-layout {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.form-container {
  flex: 1;
  min-width: 300px;
}

.progress-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  min-width: 250px;
  border-left: 1px solid #ebeef5;
}

.el-form {
  transition: opacity 0.3s ease;
}

.progress-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.progress-text {
  font-size: 20px;
  font-weight: bold;
  color: #409EFF;
}

.progress-count {
  font-size: 14px;
  color: #606266;
  margin-top: 5px;
}

.progress-label {
  margin-top: 15px;
  font-size: 16px;
  color: #606266;
}

/* 表单禁用样式 */
.form-disabled {
  opacity: 0.7;
  pointer-events: none;
}

/* 表单样式 */
.search-form .el-form-item {
  margin-bottom: 20px;
}

.button-group {
  display: flex;
  justify-content: flex-start;
  gap: 20px;
  margin-top: 10px;
}

@media screen and (max-width: 992px) {
  .content-layout {
    flex-direction: column;
  }

  .progress-container {
    border-left: none;
    border-top: 1px solid #ebeef5;
    padding-top: 30px;
    margin-top: 10px;
  }
}

@media screen and (max-width: 768px) {
  .history-sql-container {
    padding: 10px;
  }

  .icon-btn {
    width: 28px;
    height: 28px;
  }

  .icon-btn .el-icon {
    font-size: 14px;
  }

  .progress-text {
    font-size: 18px;
  }

  .progress-count {
    font-size: 12px;
  }

  .progress-label {
    font-size: 14px;
  }
}
</style>
